/**
 * Created by Administrator on 2015/12/3.
 */
"use strict";
var F = require('../../../common/function');
var organization_F = require('./organization_common');
var _o2oServiceApi = require('../../../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var _ = require('underscore');

exports.organization_update = function *(organization, key_validate_array) {
  let obj_organization_for_update = {};
  let keys_for_update_array = [];
  for (let p of key_validate_array) {
    if (organization[p] != undefined) {
      obj_organization_for_update[p] = organization[p];
      keys_for_update_array.push(p);
    }
  }
  let error_msg = organization_F.validateOrganizationFields(obj_organization_for_update, keys_for_update_array);
  if (error_msg != '') {
    return F.returnMsg(400, error_msg, 1);
  }
  obj_organization_for_update.act = 1;
  obj_organization_for_update.status = 0;
  obj_organization_for_update.id = parseInt(organization.id);

  if (obj_organization_for_update.openTime && _.v.isInt(obj_organization_for_update.openTime)) {
    obj_organization_for_update.openTime = parseInt(obj_organization_for_update.openTime);
  }
  if (obj_organization_for_update.closeTime && _.v.isInt(obj_organization_for_update.closeTime)) {
    obj_organization_for_update.closeTime = parseInt(obj_organization_for_update.closeTime);
  }
  if (obj_organization_for_update.district && !_.isEmpty(obj_organization_for_update.district)) {
    let region_code = '';
    for (let region of obj_organization_for_update.district) {
      region_code = region_code == '' ? region.code : region_code + ',' + region.code;
    }
    obj_organization_for_update.disCodes = region_code.split(',');
  }
  //if (obj_organization_for_update.lng && obj_organization_for_update.lat) {
  //  obj_organization_for_update.loc = [parseFloat(obj_organization_for_update.lng), parseFloat(obj_organization_for_update.lat)];
  //}
  //if (organization.tel && !_.isEmpty(organization.tel)) {
  //  organization.tel = organization.tel.split(',');
  //}

  delete organization.lng;
  delete organization.lat;
  delete organization.key_validate_array;
  delete organization.error_msg;
  yield organization_F.generate_img_signature(obj_organization_for_update);
  let upYunSign = obj_organization_for_update.upYunSign;

  console.log('obj_organization_for_update',obj_organization_for_update);
  let organizationResult = yield o2oServiceApi.post('shop', 'update', 1, obj_organization_for_update);
  if (parseInt(organizationResult['result']['error']) == 1 || organizationResult.status == 400) {
    return F.returnMsg(300, organizationResult['message']['msg'], 1);
  } else {
    if (!_.isEmpty(upYunSign)) {
      organizationResult['result'].upYunSign = upYunSign;
    }
    if (!_.isEmpty(organizationResult['result'].image) && _.isEmpty(upYunSign)) {
      yield organization_F.getUpYunImage(organizationResult['result']);
    }
    return F.returnMsg(200, '保存成功', 1, organizationResult['result']);
  }
};
